<?php
/**
 * Name: 角色业务实现.
 * User: 董坤鸿
 * Date: 2016/10/13
 * Time: 10:43
 */

namespace App\Services\Repo;
use App\Models\Role;
use App\Models\User;
use App\Services\ActionService;
use App\Services\Interfaces\RepoServiceInterface;
use Illuminate\Database\Eloquent\Model;

class RoleRepo implements RepoServiceInterface
{

    /**
     * 新增角色
     * @param array|null $_options
     * @return Model
     */
    public function create(array $_options = null):Model
    {
        $user = request()->user();  //获取当前登录用户信息
        $role = new Role();
        $role->title = array_get($_options, 'title', '');
        $role->actions = ActionService::addReferActions(array_get($_options, 'actions', ['-']));
        $role->company_id = $user->company_id;
        $role->creator = $user->id;
        $role->save();
        return $role;
    }

    /**
     * 角色列表
     * @param int $limit
     * @return mixed
     */
    public function read($limit = 0)
    {
        $user = request()->user();  //获取当前登录用户信息
        $role = Role::where('_id', $user->role_id)->orWhere(['creator' => $user->id, 'company_id' => $user->company_id])->get();
        return $role;
    }

    /**
     * 角色详情
     * @param array $_filter
     * @return Model
     */
    public function find(array $_filter):Model
    {
        $result = Role::find($_filter)->first();
        if ($result) {
            return $result;
        }
    }

    /**
     * 修改角色
     * @param array $_filter
     * @param array $_update_data
     * @return bool
     */
    public function update(array $_filter, array $_update_data):bool
    {
        $role = Role::find($_filter)->first();
        if (!is_null($role)) {
            $role->title = array_get($_update_data, 'title', '');
            $role->actions =
                ActionService::addReferActions(array_get($_update_data, 'actions', ['-']));
            return $role->save();
        } else {
            return false;
        }
    }

    /**
     * 删除角色
     * @param array $_filter
     * @return bool
     */
    public function delete(array $_filter):bool
    {
        $role = Role::find($_filter)->first();
        $user = User::where('role_id', $_filter['id'])->count();
        if (empty($user) && !is_null($role)) {
            return $role->delete($_filter);
        } else {
            return false;
        }
    }
}